package com.modern.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.modern.service.PaperManager;
import com.modern.service.QuestionManager;
import com.modern.model.Paper;
import com.modern.webapp.action.BaseAction;

import java.util.List;

public class PaperAction extends BaseAction implements Preparable {
	private PaperManager paperManager;
	private QuestionManager questionManager;

	private List papers;
	private Paper paper;
	private Long paperId;
	private List questionList;

	public List getQuestionList() {
		return questionList;
	}

	public void setQuestionList(List questionList) {
		this.questionList = questionList;
	}

	public void setPaperManager(PaperManager paperManager) {
		this.paperManager = paperManager;
	}

	public void setQuestionManager(QuestionManager questionManager) {
		this.questionManager = questionManager;
	}

	public List getPapers() {
		return papers;
	}

	/**
	 * Grab the entity from the database before populating with request
	 * parameters
	 */
	public void prepare() {
		if (getRequest().getMethod().equalsIgnoreCase("post")) {
			// prevent failures on new
			String paperId = getRequest().getParameter("paper.paperId");
			if (paperId != null && !paperId.equals("")) {
				paper = paperManager.get(new Long(paperId));
			}
		}
	}

	public String list() {
		papers = paperManager.getAll();
		return SUCCESS;
	}

	public void setPaperId(Long paperId) {
		this.paperId = paperId;
	}

	public Paper getPaper() {
		return paper;
	}

	public void setPaper(Paper paper) {
		this.paper = paper;
	}

	public String delete() {
		paperManager.remove(paper.getPaperId());
		saveMessage(getText("paper.deleted"));

		return SUCCESS;
	}

	public String edit() {
		if (paperId != null) {
			paper = paperManager.get(paperId);
		} else {
			paper = new Paper();
		}
		questionList = questionManager.getAll();
		return SUCCESS;
	}

	public String save() throws Exception {
		if (cancel != null) {
			return "cancel";
		}

		if (delete != null) {
			return delete();
		}

		boolean isNew = (paper.getPaperId() == null);

		paperManager.save(paper);

		String key = (isNew) ? "paper.added" : "paper.updated";
		saveMessage(getText(key));

		if (!isNew) {
			return INPUT;
		} else {
			return SUCCESS;
		}
	}
}